package com.atguigu.gulimall.product.web;

import com.alibaba.fastjson.JSON;
import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.feign.CartFeignService;
import com.atguigu.gulimall.product.service.CategoryService;
import com.atguigu.gulimall.product.vo.Catelog2Vo;
import com.atguigu.gulimall.product.vo.OrderItemVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;

@Controller
public class IndexController {
    @Autowired
    CategoryService categoryService;
    @Autowired
    CartFeignService cartFeignService;

    @GetMapping({"/","/index.html"})
    public String indexPage(Model model) throws ExecutionException, InterruptedException {
        List<CategoryEntity> categories =  categoryService.getFirstLevelCategories();
        model.addAttribute("categories",categories);
        List<OrderItemVo> cartItems = cartFeignService.getCurrentUserCartItems();
        model.addAttribute("cart",cartItems);
        Integer pageSize = 0;
        if(cartItems!=null){
            pageSize=cartItems.size();
            model.addAttribute("cartNums",pageSize);
        }
        return "index";
    }

    @GetMapping({"/index/catalog.json"})
    @ResponseBody
    public Map<String,List<Catelog2Vo>> getIndexCateroryJson(){
        Map<String, List<Catelog2Vo>> catalogJson  = categoryService.getCategoryByRedis();
        return catalogJson;
    }
}
